/**
 * 
 * The ServerConnectionManager is responsible for the connection from the application (as a server) to another (which acts as a client).
 * 
 * Author: Matthias Van Eeghem <matthias@van-eeghem.com>
 * All rights reserved.
 * 
 */

package com.bomberman.connection;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

import com.bomberman.core.GameState;
import com.bomberman.core.GameState.eState;

public class ServerConnectionManager 
{
	// Hold a list of all clients that are connected to this server
	private volatile ArrayList<ServerConnectionThread> clientList;
	// Hold the above-laying connection manager
    private volatile ConnectionManager connectionManager = null;
    // Hold the server socket that listens for new clients to connect
    private ServerSocket serverSocket = null;

    /**
     * Constructor for the ServerConnectionManager
     * 
     * @param connectionManager
     * @throws IOException
     */
	public ServerConnectionManager(ConnectionManager connectionManager) throws IOException
	{
		this.connectionManager = connectionManager;
	
		// Initialise the list of clients
		clientList = new ArrayList<ServerConnectionThread>();

		// Try listening for clients to connect
        try 
        {
    		serverSocket = new ServerSocket(6161);
        }
        catch (IOException e) 
        {
            System.out.println("Could not listen on port: 6161.");
            System.exit(-1);
        }
        
        // Set the game state
        GameState.setGameState(eState.GameStateConnected);
	}
	
	/**
	 * Run the while loop that listens for new clients
	 * 
	 * @throws IOException
	 */
	public void run() throws IOException
	{
        boolean listening = true;
        
        while(listening)
        {
        	// Start a thread for each client
	    	ServerConnectionThread thread = new ServerConnectionThread(connectionManager, serverSocket.accept());
	    	thread.start();
	    		        	
	    	clientList.add(thread);
        }
        
        serverSocket.close();
	}
	
	// Return a list of all clients that are connected to the server
	public ArrayList<ServerConnectionThread> getClientList()
	{
		return clientList;
	}
}
